﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using NLog;

namespace WcfHost {
    class WorkerWrapper {
			private static Logger logger = LogManager.GetCurrentClassLogger(); 

        /// <summary>
        /// List of all running worker threads
        /// </summary>
        List<IWcfHostWorker> _workers = new List<IWcfHostWorker>();

        /// <summary>
        /// Starts the worker threads configured in workersettings in the config file
        /// </summary>
        internal void StartWorkerThreads() {
            WcfWorkerConfigurationSection configWorkers = ConfigurationManager.GetSection("workerSettings") as WcfWorkerConfigurationSection;
            if (configWorkers == null) {
							logger.Warn("No workers found to start");
							return;

            }
            // Instantiate all defined workers  by first loading the assembly, instantiating the class and then call start.
            foreach (WorkerConfigurationElement workerElement in configWorkers.Workers) {
                // Get the service host type
                Type workerType = Type.GetType(workerElement.WorkerType, true, true);
                if (workerType == null) {
                    throw new TypeLoadException("Kunne ikke loade typen " + workerElement.WorkerType + "'.");
                }

                IWcfHostWorker iworker = (IWcfHostWorker)Activator.CreateInstance(workerType);
                iworker.Interval = workerElement.Interval;
                iworker.Name = workerElement.Name;
                // keep it in the internal collection so we are able to stop it again
                _workers.Add(iworker);
                // start the thread
                iworker.Start();
            }
        }

        /// <summary>
        /// Stops all running worker threads.
        /// </summary>
        internal void StopWorkerThreads() {
            foreach (IWcfHostWorker iwork in _workers) {
                iwork.Stop();
            }


        }

    }
}
